import pandas as pd
import geopandas as gpd
from shapely.geometry import Point, Polygon
import warnings
import time

# --- 环境设置 ---
warnings.simplefilter(action='ignore', category=FutureWarning)
try:
    from coord_convert.transform import gcj2wgs
except ImportError:
    print("❌ 致命错误：找不到 'eviltransform' 库。")
    print("   请在您能成功运行此库的Python环境中执行此脚本。")
    print("   安装命令: pip install eviltransform")
    exit()

# =========================================================================
# === 1. 文件路径定义 =====================================================
# =========================================================================
# --- 输入文件 ---
POI_CSV_IN = "poi仓山区.csv" # 您手动分类好的POI
STORES_CSV_IN = "福州市仓山区瑞幸咖啡坐标.csv"
BOUNDARY_SHP_IN = "仓山区最终完整边界.shp" # 确保这是填补了空隙的最终边界

# --- 输出文件 ---
POI_CSV_OUT = "poi仓山区1.csv"
STORES_CSV_OUT = "福州市仓山区瑞幸咖啡坐标1.csv"

def convert_points_csv_to_new_csv(input_csv: str, output_csv: str, name: str):
    """读取含GCJ-02坐标的CSV，转换为WGS-84，并保存为新的CSV。"""
    try:
        print(f"\n--- 正在处理: {input_csv} ---")
        
        # 1. 加载数据
        try:
            df = pd.read_csv(input_csv, encoding='utf-8')
        except UnicodeDecodeError:
            df = pd.read_csv(input_csv, encoding='gbk')
        print(f"  - 成功加载 {len(df)} 条记录。")
        
        # 2. 转换坐标
        print("  - 正在批量转换坐标 (GCJ-02 -> WGS-84)...")
        # 使用.itertuples()以获得更好的性能
        corrected_coords = [gcj2wgs(row.geolocation_lng, row.geolocation_lat) for row in df.itertuples()]
        
        # 3. 创建一个新的DataFrame来存储结果
        df_out = df.copy()
        df_out['geolocation_lng'] = [coord[0] for coord in corrected_coords]
        df_out['geolocation_lat'] = [coord[1] for coord in corrected_coords]
        
        # 4. 保存为新的CSV文件
        print(f"  - 正在保存为新的CSV文件: {output_csv}")
        # 使用 utf-8-sig 编码可以确保Excel打开中文时不会乱码
        df_out.to_csv(output_csv, index=False, encoding='utf-8-sig')
        
        print(f"  ✅ 成功！")
        return True
        
    except FileNotFoundError:
        print(f"  ❌ 错误：找不到输入文件 '{input_csv}'。")
        return False
    except Exception as e:
        print(f"  ❌ 处理文件时发生未知错误: {e}")
        return False

# =========================================================================
# === 3. 主执行流程 =======================================================
# =========================================================================
def main():
    start_time = time.time()
    print("========================================================")
    print("=== 开始执行点数据坐标系批量转换脚本 (输出为CSV) ===")
    print("========================================================")
    
    success1 = convert_points_csv_to_new_csv(POI_CSV_IN, POI_CSV_OUT, "POI")
    success2 = convert_points_csv_to_new_csv(STORES_CSV_IN, STORES_CSV_OUT, "瑞幸门店")

    total_time = time.time() - start_time
    print(f"\n--- 流程执行完毕，总耗时: {total_time:.2f} 秒 ---")
    
    if success1 and success2:
        print(f"🎉 [成功] 所有文件转换完成！")
        print("   您现在可以在主数据准备脚本中使用以下新生成的CSV文件了:")
        print(f"   - {POI_CSV_OUT}")
        print(f"   - {STORES_CSV_OUT}")
    else:
        print(f"⚠️ [部分失败] 请检查上面的错误日志。")

if __name__ == "__main__":
    main()